package fhq.hcmute.qrcode.detector;

import java.util.ArrayList;
import java.util.List;

import fhq.hcmute.qrcode.common.BinaryImage;
import fhq.hcmute.qrcode.util.QRCodeException;

public class AlignmentPatternFinder {

	private final BinaryImage image;
	private final List<PatternPoint> possibleCenters;
	private final int startX;
	private final int startY;
	private final int width;
	private final int height;
	private final float moduleSize;

	AlignmentPatternFinder(BinaryImage image, int startX, int startY,
			int width, int height, float moduleSize) {
		this.image = image;
		this.possibleCenters = new ArrayList<PatternPoint>(5);
		this.startX = startY;
		this.startY = startX;
		this.width = width;
		this.height = height;
		this.moduleSize = moduleSize;
	}

	public PatternPoint find() throws QRCodeException {
		int startX = this.startX;
		int height = this.height;
		int maxJ = startX + width;
		int middleI = startY + (height >> 1);
		int[] stateCount = new int[3];
		for (int iGen = 0; iGen < height; iGen++) {
			int i = middleI
					+ ((iGen & 0x01) == 0 ? (iGen + 1) >> 1
							: -((iGen + 1) >> 1));
			stateCount[0] = 0;
			stateCount[1] = 0;
			stateCount[2] = 0;
			int j = startX;
			int currentState = 0;
			while (j < maxJ) {
				if (image.getPixel(i, j)) {
					if (currentState == 1) { // Counting black pixels
						stateCount[currentState]++;
					} else { // Counting white pixels
						if (currentState == 2) { // A winner?
							if (foundPatternCross(stateCount)) { // Yes
								PatternPoint confirmed = handlePossibleCenter(
										stateCount, i, j);
								if (confirmed != null) {
									return confirmed;
								}
							}
							stateCount[0] = stateCount[2];
							stateCount[1] = 1;
							stateCount[2] = 0;
							currentState = 1;
						} else {
							stateCount[++currentState]++;
						}
					}
				} else { // White pixel
					if (currentState == 1) { // Counting black pixels
						currentState++;
					}
					stateCount[currentState]++;
				}
				j++;
			}
			if (foundPatternCross(stateCount)) {
				PatternPoint confirmed = handlePossibleCenter(stateCount, i,
						maxJ);
				if (confirmed != null) {
					return confirmed;
				}
			}

		}
		if (!possibleCenters.isEmpty()) {
			return possibleCenters.get(0);
		}
		return null;
	}

	private static float centerFromEnd(int[] stateCount, int end) {
		return (float) (end - stateCount[2]) - stateCount[1] / 2.0f;
	}

	private boolean foundPatternCross(int[] stateCount) {

		float moduleSize = this.moduleSize;
		float maxVariance = moduleSize / 2.0f;
		for (int i = 0; i < 3; i++) {
			if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) {
				return false;
			}
		}
		return true;
	}

	private float crossCheckVertical(int startI, int centerJ, int maxCount,
			int originalStateCountTotal) {
		BinaryImage image = this.image;

		int maxI = image.getHeight();
		int[] stateCount = new int[3];

		// Start counting up from center
		int i = startI;
		while (i >= 0 && image.getPixel(i, centerJ)
				&& stateCount[1] <= maxCount) {
			stateCount[1]++;
			i--;
		}
		// If already too many modules in this state or ran off the edge:
		if (i < 0 || stateCount[1] > maxCount) {
			return Float.NaN;
		}
		while (i >= 0 && !image.getPixel(i, centerJ)
				&& stateCount[0] <= maxCount) {
			stateCount[0]++;
			i--;
		}
		if (stateCount[0] > maxCount) {
			return Float.NaN;
		}

		// Now also count down from center
		i = startI + 1;
		while (i < maxI && image.getPixel(i, centerJ)
				&& stateCount[1] <= maxCount) {
			stateCount[1]++;
			i++;
		}
		if (i == maxI || stateCount[1] > maxCount) {
			return Float.NaN;
		}
		while (i < maxI && !image.getPixel(i, centerJ)
				&& stateCount[2] <= maxCount) {
			stateCount[2]++;
			i++;
		}
		if (stateCount[2] > maxCount) {
			return Float.NaN;
		}

		int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
		if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
			return Float.NaN;
		}

		return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i)
				: Float.NaN;
	}

	private PatternPoint handlePossibleCenter(int[] stateCount, int i, int j) {
		int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
		float centerJ = centerFromEnd(stateCount, j);
		float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1],
				stateCountTotal);
		if (!Float.isNaN(centerI)) {
			float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;
			for (PatternPoint center : possibleCenters) {
				PatternPoint pointTemp = new PatternPoint(centerI, centerJ,
						estimatedModuleSize);
				if (center.equals(pointTemp)) {
					return center.combine(new PatternPoint(centerI, centerJ,
							estimatedModuleSize));
				}
			}
			PatternPoint point = new PatternPoint(centerI, centerJ,
					estimatedModuleSize);
			possibleCenters.add(point);
		}
		return null;
	}
}
